package com.yhy.job.service.mng;

import com.yhy.common.constants.BusModuleType;
import com.yhy.common.dto.BaseEntity;
import com.yhy.common.exception.BusinessException;
import com.yhy.common.service.BaseMngService;
import com.yhy.common.utils.JsonUtils;
import com.yhy.job.dao.QuartzJobMngDao;
import com.yhy.job.dto.QuartzJobDTO;
import com.yhy.job.service.QuartzJobService;
import com.yhy.job.utils.QuartzJobManage;
import com.yhy.job.vo.mng.QuartzJobMngVO;
import com.yhy.job.vo.QuartzJobVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/*
 *
 *  * *
 *  *  * <br>
 *  *  * <b>功能：</b><br>
 *  *  * <b>作者：</b>yanghuiyaun<br>
 *  *  * <b>日期：</b> 19-11-13 下午4:32 <br>
 *  *  * <b>版权所有：<b>版权所有(C) 2019<br>
 *  *
 *
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class QuartzJobMngService extends BaseMngService<QuartzJobDTO,QuartzJobMngVO> {

    @Autowired
    private QuartzJobMngDao quartzJobMngDao;
    @Autowired
    private QuartzJobService quartzJobService;
    @Autowired
    private QuartzJobManage quartzJobManage;

    @Override
    protected QuartzJobMngDao getBaseMngDao() {
        return quartzJobMngDao;
    }

    @Override
    public String getBusModule() {
        return BusModuleType.MD_QUARTZ_JOB_MNG.getVal();
    }

    @Override
    public QuartzJobService getBaseMainService() {
        return quartzJobService;
    }


    public List<QuartzJobMngVO> findAllValidJob() {
        return getBaseMngDao().findAllValidJob();
    }


    public void doPause(String id) {
        QuartzJobMngVO quartzJobMngVO = findByMainId(id);
        if(quartzJobMngVO.getPause()) {
            quartzJobMngVO.setPause(false);
            quartzJobService.update(JsonUtils.tranObject(quartzJobMngVO, QuartzJobVO.class));
            quartzJobManage.resumeJob(quartzJobMngVO);
        } else {
            quartzJobMngVO.setPause(true);
            quartzJobService.update(JsonUtils.tranObject(quartzJobMngVO, QuartzJobVO.class));
            quartzJobManage.pauseJob(quartzJobMngVO);
        }
    }

    public void doRunJob(String id) {
        QuartzJobMngVO quartzJobMngVO = findByMainId(id);
        if(quartzJobMngVO.getRunning()) {
            throw new BusinessException("任务正在执行...");
        }
        quartzJobManage.runJobNow(quartzJobMngVO);
    }

    @Override
    protected void afterProcessCustomDataOfSave(QuartzJobDTO baseDTO) {
        super.afterProcessCustomDataOfSave(baseDTO);

        QuartzJobMngVO quartzJobMngVO = findByMainId(baseDTO.getBusMainData().getId());
        quartzJobManage.updateJob(quartzJobMngVO);
    }

    @Override
    protected void beforeDeleteOfProcess(QuartzJobMngVO busMainData) {
        super.beforeDeleteOfProcess(busMainData);
        quartzJobManage.deleteJob(busMainData);
    }

}
